<?php
class AccRole_model extends TP_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->table = 'rel_role_account';
    }
    /**
     * [ setRole]
     * @Name        setRole
     * @Description 设置角色
     * @Author      LiAnXu
     * @Date 2020-12-11 13:59:14 星期五
     * @param  $role_id     role_id    
     * @param  $list        用户数据[array]
     * @param  $add        是否添加
     * @return      [type]                   [description]
     */
    public function setRole($role_id,$list,$add)
    {   
        $list_count=count($list);  
        // 获取所有有该角色的数据      
        $connar1['join']=array('tp_account','tp_account.uuid=tp_rel_role_account.uuid');
        $connar1['where']=sql_format("role_id={0} and tp_rel_role_account.is_delete={1}",$role_id,DeleteState::UnDelete[TPEnum::Value]);
        $all_list=$this->get_list_full($connar1);
        $all_uuid_arr=array_column($all_list,'uuid');
        if($list_count>0){
            $admin_id=implode(',',$list);
            $connar['where']=sql_format('tp_account.id in ({0}) and tp_rel_role_account.is_delete={1}',$admin_id,DeleteState::UnDelete[TPEnum::Value]);
            $connar['orderby']=sql_format("field(tp_account.id,{0})",$admin_id);
            $connar['join']=array('tp_rel_role_account','tp_account.uuid=tp_rel_role_account.uuid');
            $connar['items']='tp_account.*,GROUP_CONCAT(role_id) role_id';
            $connar['groupby']="tp_account.uuid";
            $data=$this->Account_model->get_list_full($connar);
            foreach ($data as $k => $v) {
                $del[$v['uuid']]=$v;
            }
            $data_count=count($data);
            // 判断条数是否正确
            if($list_count!=$data_count){
                exit(retJson(ErrCode::ErrCode_10004));
            }
            $list_uuid_arr=array_column($data,'uuid');
            $add_list=array_diff($list_uuid_arr,$all_uuid_arr);
            if($add){
                foreach ($add_list as $k => $v) {
                    $this->add(array('uuid'=>$v,'role_id'=>$role_id));
                }
            }else{
                // 删除指定账户的数据,仅当多个角色时
                foreach ($list_uuid_arr as $k => $v) {
                    $role_count=count(explode(',',$del[$v]['role_id']));
                    if($role_count>1){
                        $this->update(array('is_delete'=>DeleteState::Delete[TPEnum::Value]),array('uuid'=>$v,'role_id'=>$role_id));
                    }                    
                }
            }            
        }
        
        return true;
    }
}
